const express = require("express");
const pool = require("../pool.js");

const evalRouter = express.Router();
module.exports = evalRouter;

// 根据被评价者查找评价
evalRouter.get("/find", (req, res,next) => {
  var page = req.query.page || 1;
  const pagesize = 10;
  var offset = (page - 1) * pagesize;
  var evaname = req.query.evaname;
  var sql = `select count(evaid) as count from evaluate where evaname=?`;
  pool.query(sql, [evaname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    let pagecount = Math.ceil(r[0].count / pagesize);
    sql = `select * from evaluate where evaname=? limit ?,?`;
    pool.query(sql, [evaname, offset, pagesize], (err, r) => {
      if (err) {
        next(err);
        return;
      }
      if (r.length != 0) res.send({ code: 200, data: r, pagecount });
      else res.send({ code: 201, msg: "无数据" });
    });
  });
});
// 新建评价
evalRouter.post("/insert", (req, res,next) => {
  var nickname = req.body.nickname;
  var evaname = req.body.evaname;
  var evatime = req.body.evatime;
  var evadetail = req.body.evadetail;
  console.log(nickname, evaname, evatime, evadetail);
  var sql = `insert into evaluate values(null,?,?,?,?)`;
  pool.query(sql, [nickname, evaname, evatime, evadetail], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.affectedRows != 0) res.send({ code: 200, msg: "发布评价成功" });
    else res.send({ code: 500, msg: "发布评价失败" });
  });
});
// 根据评价者和评价时间删除评价
evalRouter.delete("/delete", (req, res,next) => {
  var nickname = req.query.nickname;
  var evatime = req.query.evatime;
  if (nickname == "" || evatime == "") {
    res.send({ code: 202, msg: "输入不能为空！" });
    return;
  }
  var sql = `delete from evaluate where nickname=? and evatime=?`;
  pool.query(sql, [nickname, evatime], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r.affectedRows) {
      res.send({ code: 201, msg: "找不到该评价" });
    } else {
      res.send({ code: 200, msg: "删除成功" });
    }
  });
});
// 根据评价id删除评价
evalRouter.delete("/deleteById", (req, res,next) => {
  var evaid = req.query.evaid;
  console.log(evaid);
  var sql = `delete from evaluate where evaid=?`;
  pool.query(sql, [evaid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.affectedRows != 0) {
      res.send({ code: 200, msg: "删除成功" });
    } else {
      res.send({ code: 201, msg: "删除失败" });
    }
  });
});
